package com.xbongbong.crm.perform.query.list.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmListQryService;
import com.xbongbong.crm.handle.analysis.ContactListAnalysisDataHandler;
import com.xbongbong.paas.call.AliyunCall;
import com.xbongbong.paas.call.CallCenterService;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.HandleExplainHelp;
import com.xbongbong.parent.pojo.list.ConditionListPojo;
import com.xbongbong.parent.pojo.list.ConditionListResultPoJo;
import com.xbongbong.parent.pojo.list.DataAnalysisListPojo;
import com.xbongbong.parent.pojo.list.FieldListPojo;
import com.xbongbong.parent.pojo.list.PermissionListPojo;
import com.xbongbong.pro.applist.pojo.AppListPojo;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author sunshaoxiang
 * @ClassName ContactListServiceImpl
 * @Description 联系人列表业务层
 * @Date 2022/5/13 17:00
 * @Version 1.0
 **/
@Service
public class ContactListServiceImpl extends AbstractCrmListQryService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContactListServiceImpl.class);

    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private HandleExplainHelp handleExplainHelp;
    @Resource
    private CallCenterService callCenterService;
    @Resource
    private ContactListAnalysisDataHandler contactListAnalysisDataHandler;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private AliyunCall aliyunCall;


    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.CONTACT.getCode());
    }

    @Override
    public List<ConditionsEntityExt> getPermission(PermissionListPojo permissionListPojo) throws XbbException {
        UserVO userVO = permissionListPojo.getUserVO();
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>();
        if (userVO.isMaxDataPermission()){
            return conditionsEntityExtList;
        }

        return getTeamUserPermission(userVO);
    }


    @Override
    public ConditionListResultPoJo getCondition(ConditionListPojo conditionListPojo) throws XbbException {
        try {
            //封装公共查询条件
            commonCondition(conditionListPojo);
            webCommonFilter(conditionListPojo);
            return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
        } catch (XbbException e) {
            LOGGER.error("com.xbongbong.crm.list.ContactListServiceImpl.getCondition error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }



    @Override
    public ConditionListResultPoJo mobileGetCondition(ConditionListPojo conditionListPojo) throws XbbException {
        //封装公共查询条件
        commonCondition(conditionListPojo);

        // app端独有范围筛选
        saasListDataPermissionHelp.dingtalkRangeScreen(conditionListPojo.getConditionList(), conditionListPojo.getUserVO(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), conditionListPojo.getSubBusinessType(), conditionListPojo.getPlatform());
        return new ConditionListResultPoJo(conditionListPojo.getConditionList(), conditionListPojo.getShouldConditionList());
    }

    @Override
    public HandleExplainPojo getExplain(FieldListPojo fieldListPojo) throws XbbException {
        List<String> fieldList = new ArrayList<>();
        List<FieldAttrEntity> explainList = commonGetExplain(fieldListPojo, fieldList);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(explainList, fieldListPojo.getForm(), fieldListPojo.getCorpid(), fieldListPojo.getUserVO().getUserId(), fieldListPojo.getUserVO(), true, fieldListPojo.getSubBusinessType());
        HandlerExplainVO handlerExplainVO = handleExplainHelp.handleExplain(handlerExplainDTO);

        HandleExplainPojo handleExplainPojo = new HandleExplainPojo();
        explainList = handlerExplainVO.getHeadList();
        handleExplainPojo.setExplainList(explainList);
        handleExplainPojo.setFieldList(fieldList);
//        handleExplainPojo.setUpdateTime(paasFormExplainEntity.getUpdateTime());

        return handleExplainPojo;
    }

    @Override
    public List<PaasFormDataEntityExt> webDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();
        FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(),dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        formDataListVO.setPaasFormDataESList(formDataList);
        formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());
        if (formDataList == null || formDataList.isEmpty()) {
            return formDataList;
        }

        contactListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
        contactListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, formDataListDTO.getAnalysisAmountOfThousandBitsWithOriginalValue());
        return formDataListVO.getPaasFormDataESList();
    }

    @Override
    public List<PaasFormDataEntityExt> dingtalkDataAnalysis(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        try {
            List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();

            FormDataListDTO formDataListDTO = new FormDataListDTO(dataAnalysisListPojo.getCorpid(), dataAnalysisListPojo.getFormId(), dataAnalysisListPojo.getSaasMark(), dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType(), dataAnalysisListPojo.getDistributorMark(), dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getAnalysisAmountOfThousandBitsWithOriginalValue());

            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setHeadList(dataAnalysisListPojo.getExplainList());
            formDataListVO.setPaasFormDataESList(formDataList);
            formDataListVO.setForm(dataAnalysisListPojo.getForm());
            formDataListVO.setForm(dataAnalysisListPojo.getForm());

            contactListAnalysisDataHandler.analysisDataList(formDataListDTO, formDataListVO);
            contactListAnalysisDataHandler.analysisAmountOfThousandBits(formDataListVO, false);


            // 摘要和标题的封装
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, formDataListDTO.getFormMap(), dataAnalysisListPojo.getFormIdAndHeadListMap());
            return formDataListVO.getPaasFormDataESList();
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.crm.list.ContactListServiceImpl.dingtalkDataAnalysis error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override

    public List<AppListPojo> dingtalkOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        //todo 参考customer 看看是否需要更改
        List<AppListPojo> appListPojos = new ArrayList<>();
        List<Long> customerIdIn = new ArrayList<>();
        String corpid = dataAnalysisListPojo.getCorpid();
        Long formId = dataAnalysisListPojo.getFormId();
        String userId = dataAnalysisListPojo.getUserId();
        Integer businessType = dataAnalysisListPojo.getBusinessType();
        List<PaasFormDataEntityExt> formDataList = dataAnalysisListPojo.getFormDataList();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(JSON.toJSONString(dataAnalysisListPojo.getExplainList()));
        customerIdIn.add(-1L);
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        for(PaasFormDataEntityExt entity : formDataList){
            JSONObject data = entity.getData();
            SaveFormatHelp.formatLinkBusiness4Save(data, ContactEnum.CUSTOMER_NAME.getAttr(), ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), ContactEnum.CUSTOMER_NAME.getFieldType());
            Long customerId;
            try {
                customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, ContactEnum.CUSTOMER_NAME.getAttr(), -1L);
            } catch (Exception e) {
                customerId = -1L;
            }
            customerIdIn.add(customerId);
        }

        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

        boolean isActiveCall = callCenterService.isOpenCallDingTalk(corpid, userId);

        for (PaasFormDataEntityExt entity : formDataList) {
            JSONObject data = entity.getData();

            Long id = entity.getDataId();
            String name = FastJsonHelper.getStringOrDefaultFromFormData(data, ContactEnum.NAME.getAttr(), "");
            FieldAttrEntity contactNameExplain = null;
            //电话可见判断
            Integer contactAttrVisible = 0;
            for (FieldAttrEntity explain : explainList) {
                if (Objects.equals(explain.getAttr(), ContactEnum.NAME.getAttr()) && Objects.equals(explain.getIsOpen(), 1)) {
                    contactNameExplain = explain;
                }
                if (Objects.equals(explain.getAttr(), ContactEnum.PHONE.getAttr()) && Objects.equals(explain.getIsOpen(), 1)) {
                    contactAttrVisible = explain.getVisible();
                }
            }

            if (contactNameExplain != null && contactNameExplain.getVisible() == 0) {
                name = StringConstant.INVISIBLE_VALUE;
            }
            JSONObject superScript = new JSONObject();
            JSONObject others = new JSONObject();


            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<SummaryDataPoJo> lablesList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.LABELS_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            /*-- 其他 -*/
            // 话务中心用户可以看到拨号列表
            JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ContactEnum.PHONE.getAttr(), new JSONArray());
            commonHelp.setContactPhone(others, contactPhoneArray, isActiveCall, contactAttrVisible, entity, data);
            boolean showAliyunCall = AliyunCall.checkShowCall(corpid, explainMap, entity);
            Boolean activeAliyunCall = callCenterService.isActiveAliyunCall(corpid, userId).IsActiveAliyunAndHasRole();
            activeAliyunCall = true;
            if(activeAliyunCall&&showAliyunCall){
                superScript.put("activeAliyunCall", 1);
            }else{
                superScript.put("activeAliyunCall", 0);
            }
            // 联系人头像
            JSONArray avatarArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ContactEnum.AVATAR.getAttr(), new JSONArray());
            String avatar = CollectionsUtil.isNotEmpty(avatarArray) ? avatarArray.getString(0) : "";
            others.put("avatar", avatar);
            AppListPojo appListPojo = new AppListPojo(id, titleList, summaryList, superScript, lablesList, others, entity.getAppId(), entity.getMenuId(), entity.getFormId());
            appListPojo.setBusinessType(businessType);
            appListPojo.setDataId(id);
            appListPojos.add(appListPojo);
        }
        return appListPojos;
    }

    @Override
    public void webOperate(DataAnalysisListPojo dataAnalysisListPojo) throws XbbException {
        String corpid = dataAnalysisListPojo.getCorpid();
        List<PaasFormDataEntityExt> dataList = dataAnalysisListPojo.getFormDataList();
        List<FieldAttrEntity> explainList = dataAnalysisListPojo.getExplainList();
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(explainList);
        Set<String> userIdSet = new HashSet<>();
        List<Long> dataIdIn = new ArrayList<>();
        dataList.forEach(item->{
            dataIdIn.add(item.getId());
        });
        Map<Long, List<String>> mainUserIdIn = new HashMap<>(dataIdIn.size());
        Map<Long, List<String>> coUserIdIn = new HashMap<>(dataIdIn.size());
        businessUserTeamHelp.getUserIdMapSetShow(userIdSet, dataIdIn, corpid, dataAnalysisListPojo.getBusinessType(), false, mainUserIdIn, coUserIdIn, DelEnum.NORMAL.getDel());

        //呼叫按钮
        AliyunCall aliyunCallPojo = aliyunCall.setAliCallField( corpid, dataAnalysisListPojo.getUserVO(), dataAnalysisListPojo.getExplainList(), mainUserIdIn, coUserIdIn, dataAnalysisListPojo.getBusinessType(), dataAnalysisListPojo.getSubBusinessType());
        dataList.forEach(item->{
            aliyunCall.setCallData( aliyunCallPojo, corpid, item, explainMap, ContactEnum.PHONE.getAttr());
        });
    }

    /**
     * 封装公共查询条件：分组条件
     * @param conditionListPojo
     */
    private void commonCondition(ConditionListPojo conditionListPojo) throws XbbException {
        setCommonCondition(conditionListPojo);
    }

}
